package com.wondertek.service.service.sys.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wondertek.common.dict.AutoDictService;
import com.wondertek.common.enums.StatusEnum;
import com.wondertek.common.exception.AppException;
import com.wondertek.common.util.base.ServletUtil;
import com.wondertek.service.dto.sys.req.SysDictAddReq;
import com.wondertek.service.dto.sys.req.SysDictQueryChildrenReq;
import com.wondertek.service.dto.sys.req.SysDictQueryReq;
import com.wondertek.service.dto.sys.req.SysDictUpdateReq;
import com.wondertek.service.entity.sys.SysDictPo;
import com.wondertek.service.mapper.sys.SysDictMapper;
import com.wondertek.service.service.sys.ISysDictService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author xqs
 */
@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDictPo>
    implements ISysDictService, AutoDictService {


    @Override
    public Page<SysDictPo> findChildrenPage(SysDictQueryChildrenReq sysDictQueryChildrenReq) {
        LambdaQueryWrapper<SysDictPo> wrapper = new LambdaQueryWrapper<>();
        if(ObjectUtil.isNotEmpty(sysDictQueryChildrenReq.getDictName())){
            wrapper.like(SysDictPo::getDictName,sysDictQueryChildrenReq.getDictName());
        }
        // 父级id
        if(ObjectUtil.isNotEmpty(sysDictQueryChildrenReq.getParentDictId())){
            wrapper.eq(SysDictPo::getParentId,sysDictQueryChildrenReq.getParentDictId());
        }
        // 父级code
        if(ObjectUtil.isNotEmpty(sysDictQueryChildrenReq.getParentDictCode())){
            SysDictPo parentDict = this.lambdaQuery().eq(SysDictPo::getDictCode,
                    sysDictQueryChildrenReq.getParentDictCode())
                    .eq(SysDictPo::getParentId,"0")
                    .one();
            wrapper.eq(SysDictPo::getParentId,parentDict.getId());
        }
        if(ObjectUtil.isNotEmpty(sysDictQueryChildrenReq.getStatus())){
            wrapper.eq(SysDictPo::getStatus,sysDictQueryChildrenReq.getStatus());
        }
        wrapper.orderByDesc(SysDictPo::getSort);
        wrapper.orderByDesc(SysDictPo::getCreateTime);
        return this.page(new Page<>(sysDictQueryChildrenReq.getPageNo(),sysDictQueryChildrenReq.getPageSize()),wrapper);
    }

    @Override
    public List<SysDictPo> findTree(SysDictQueryReq sysDictQueryReq) {
        LambdaQueryWrapper<SysDictPo> wrapper = new LambdaQueryWrapper<>();
        if(ObjectUtil.isNotEmpty(sysDictQueryReq.getDictName())){
            wrapper.like(SysDictPo::getDictName,sysDictQueryReq.getDictName());
        }
        if(ObjectUtil.isNotEmpty(sysDictQueryReq.getStatus())){
            wrapper.eq(SysDictPo::getStatus,sysDictQueryReq.getStatus());
        }
        wrapper.orderByDesc(SysDictPo::getSort);
        wrapper.orderByDesc(SysDictPo::getCreateTime);
        List<SysDictPo> sysDictPos = this.list(wrapper);
        return toTree(sysDictPos,"0");
    }

    @Override
    public List<SysDictPo> findListByDictCode(String dictCode) {
        SysDictPo parentDict = this.lambdaQuery()
                .eq(SysDictPo::getParentId,"0")
                .eq(SysDictPo::getDictCode, dictCode).one();
        if(parentDict == null){
            throw new AppException("dict.not.config");
        }
        return this.lambdaQuery().eq(SysDictPo::getParentId,parentDict.getId())
                .eq(SysDictPo::getStatus, StatusEnum.ENABLE.getCode())
                .orderByDesc(SysDictPo::getSort).orderByDesc(SysDictPo::getCreateTime).list();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SysDictAddReq sysDictAddReq) {
        SysDictPo sysDictPo = new SysDictPo();
        BeanUtil.copyProperties(sysDictAddReq,sysDictPo);
        if(ObjectUtil.isEmpty(sysDictPo.getParentId())){
            sysDictPo.setParentId("0");
        }
        String dictCode = RandomUtil.randomStringUpper(6);
        sysDictPo.setDictCode(dictCode);
        long count = this.lambdaQuery().eq(SysDictPo::getDictName, sysDictAddReq.getDictName())
                .eq(SysDictPo::getParentId,sysDictPo.getParentId())
                .count();
        if (count > 0) {
            throw new AppException("dict.name.repeat");
        }
        this.save(sysDictPo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysDictUpdateReq sysDictUpdateReq) {
        SysDictPo sysDictPo = this.getById(sysDictUpdateReq.getId());
        if(!StrUtil.equals(sysDictPo.getDictName(),sysDictUpdateReq.getDictName())){
            long count = this.lambdaQuery().eq(SysDictPo::getDictName, sysDictUpdateReq.getDictName())
                    .eq(SysDictPo::getParentId,sysDictPo.getParentId())
                    .count();
            if (count > 0) {
                throw new AppException("dict.name.repeat");
            }
        }
        BeanUtil.copyProperties(sysDictUpdateReq,sysDictPo);
        sysDictPo.setUpdateBy(null);
        sysDictPo.setUpdateTime(null);
        this.updateById(sysDictPo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void disable(String id) {
        SysDictPo sysDictPo = this.getById(id);
        sysDictPo.setStatus(StatusEnum.DISABLE.getCode());
        this.updateById(sysDictPo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void enable(String id) {
        SysDictPo sysDictPo = this.getById(id);
        sysDictPo.setStatus(StatusEnum.ENABLE.getCode());
        this.updateById(sysDictPo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        this.removeById(id);
    }

    @Override
    public List<SysDictPo> findCacheList() {
        HttpServletRequest request = ServletUtil.getHttpServletRequest();
        if(request!=null){
            Object cacheSysDictPos = request.getAttribute("cacheSysDictPos");
            if(cacheSysDictPos==null){
                cacheSysDictPos = this.list();
                request.setAttribute("cacheSysDictPos",cacheSysDictPos);
            }
            return (List<SysDictPo>) cacheSysDictPos;
        }
        return this.list();
    }

    private List<SysDictPo> toTree(List<SysDictPo> listData, String parentId) {
        List<SysDictPo> treeData = new ArrayList<>();
        Iterator<SysDictPo> it = listData.iterator();
        while (it.hasNext()){
            SysDictPo item =it.next();
            if (item.getParentId().equals(parentId)){
                SysDictPo sysDictPo = new SysDictPo();
                BeanUtil.copyProperties(item,sysDictPo);
                treeData.add(sysDictPo);
                //把已经添加了的数据删除，减少迭代次数
                it.remove();
            }
        }
        for(SysDictPo item:treeData){
            item.setChildren(toTree(listData,item.getId()));
        }
        return CollUtil.isEmpty(treeData) ? new ArrayList<>() : treeData;
    }

    @Override
    public String getDictName(String type, String code) {
        List<SysDictPo> dicts = this.findCacheList();
        String parentId = dicts.stream()
                .filter(v -> v.getDictCode().equals(type)&& "0".equals(v.getParentId()))
                .toList().get(0).getId();
        SysDictPo dictPo = dicts.stream()
                .filter(v -> v.getParentId().equals(parentId))
                .filter(v -> v.getDictCode().equals(code))
                .toList().get(0);
        return dictPo.getDictName();
    }
}
